<template>
  <div class="slide-text-container">
    <div class="slide-text-wrapper"></div>
  </div>
</template>

<script>
export default {
  name: 'ZSlideText',
  props: {
    slideText: {
      type: String,
      default: ''
    }
  },
  watch: {
    slideText: {
      handler: function(val) {
        this.$nextTick(_ => {
          this.init(val)
        })
      },
      immediate: true
    }
  },
  data() {
    return {
      curIndex: 0,
      singleInterval: null,
      allInterval: null
    }
  },
  beforeDestroy() {
    this.clearData()
  },
  methods: {
    init(val) {
      this.clearData()

      const wrapper = document.querySelector('.slide-text-wrapper')
      wrapper.innerHTML = ''

      if (!val) {
        return
      }
      
      const interval = 100
      this.singleInterval = setInterval(() => {
        if (this.curIndex >= val.length) {
          clearInterval(this.singleInterval)
          this.singleInterval = null
          return
        }

      	const word = val[this.curIndex];
      	const spanEle = document.createElement('span')
        spanEle.setAttribute('class', 'slide-text-letter')
      	spanEle.innerHTML = word // ? word : '&nbsp;'
      	wrapper.append(spanEle);
      	this.curIndex++;
      }, interval);

      this.allInterval = setInterval(() => {
        this.init(val)
      }, interval * (val.length + 100))
    },
    clearData() {
      if (this.singleInterval) {
        clearInterval(this.singleInterval)
        this.singleInterval = null
      }
      if (this.allInterval) {
        clearInterval(this.allInterval)
        this.allInterval = null
      }
      this.curIndex = 0
    }
  }
}
</script>

<style lang="scss" scoped>
.slide-text-container {
  display: inline-block;
  box-sizing: border-box;
  padding: 0px;
  height: 30px;
  overflow: hidden;
  font-family: 'Bowlby One SC', cursive;
}

</style>

<style lang="scss">
.slide-text-letter {
  display: inline-block;
  min-width: 6px;
  letter-spacing: 1px;
  animation: letterZoom 1s ease;
}

@keyframes letterZoom {
  0% {
    transform: scale(0) translateX(20vw);
  }
  80% {
    transform: scale(3, 1.5);
    text-shadow: 30px 30px 30px black;
  }
  100% {
    text-shadow: 0px 2px 0px black;
  }
}
</style>